package com.jindun.paper.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jindun.paper.dao.ClientTypeRepository;
import com.jindun.paper.model.ClientType;
import com.jindun.paper.service.ClientTypeService;

@Service
public class ClientTypeServiceImpl implements ClientTypeService {

	@Autowired
	private ClientTypeRepository clientTypeRepository;
	
	
	
	@Autowired
	private EntityManager entityManager;
	
	
	
	@Override
	@Transactional(readOnly=true)
	public ClientType getOne(Integer clientTypeId) {
		ClientType clientType = clientTypeRepository.getOne(clientTypeId);
		Hibernate.initialize(clientType);
		return clientType;
	}


	@Override
	@Transactional(readOnly=true)
	public List<ClientType> findAll() {
	
		return this.clientTypeRepository.findAll();
		
	}


	@Override
	public boolean isTypeNameUnique(Integer clientTypeId, String clientTypeName) {

		
		StringBuilder jql = new StringBuilder();
		jql.append("from ClientType c where c.name = ? ");
		if (clientTypeId != null) {
			jql.append(" and c.id != ?");
		}
		
		Query query = this.entityManager.createQuery(jql.toString());
		query.setParameter(1, clientTypeName);
		
		if (clientTypeId != null) {
			query.setParameter(2, clientTypeId);
		}
		
		
		return query.getResultList().size() == 0;
	
	}
	
	

}
